{% extends "home/base.html" %}
{% block fence %} class="active" {% endblock %}
{% block page_title %} 生活圈分类结果 {% endblock %}

{% block content %}
<div class="col-lg-12">
    <div class="card">
        <div class="card-header">
            <h6 class="card-title">生活圈分类结果</h6>
            <div class="card-tools">
                <form id="searchForm" class="form-inline">
                    <div class="input-group input-group-sm">
                        <input type="text" id="searchInput" name="search_term" 
                               class="form-control" placeholder="搜索..." 
                               value="{{ search_term }}">
                        <div class="input-group-append">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i> 确定
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table id="dataTable" class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            {% for column in columns %}
                            <th>{{ column }}</th>
                            {% endfor %}
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for row in table_data %}
                        <tr data-id="{{ loop.index0 }}">
                            {% for column in columns %}
                            <td>{{ row[column] }}</td>
                            {% endfor %}
                            <td>
                                <button class="btn btn-sm btn-primary edit-btn">
                                    <i class="fas fa-edit"></i> 编辑
                                </button>
                                <button class="btn btn-sm btn-success save-btn" style="display: none;">
                                    <i class="fas fa-check"></i> 保存
                                </button>
                                <button class="btn btn-sm btn-secondary cancel-btn" style="display: none;">
                                    <i class="fas fa-times"></i> 取消
                                </button>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            
            <!-- 分页控件 -->
            <div class="row mt-3">
                <div class="col-md-6">
                    <div class="dataTables_info">
                        显示 {{ (current_page-1)*10 + 1 }} 到 {{ [current_page*10, table_data|length + (current_page-1)*10]|min }} 条，共 {{ total_pages*10 }} 条记录
                    </div>
                </div>
                <div class="col-md-6">
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-end">
                            <li class="page-item {% if current_page == 1 %}disabled{% endif %}">
                                <a class="page-link" href="?page=1&search_term={{ search_term }}" aria-label="First">
                                    <span aria-hidden="true">首页</span>
                                </a>
                            </li>
                            <li class="page-item {% if current_page == 1 %}disabled{% endif %}">
                                <a class="page-link" href="?page={{ current_page-1 }}&search_term={{ search_term }}" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            
                            {% for p in range(1, total_pages+1) %}
                                {% if p >= current_page-2 and p <= current_page+2 %}
                                <li class="page-item {% if p == current_page %}active{% endif %}">
                                    <a class="page-link" href="?page={{ p }}&search_term={{ search_term }}">{{ p }}</a>
                                </li>
                                {% endif %}
                            {% endfor %}
                            
                            <li class="page-item {% if current_page == total_pages %}disabled{% endif %}">
                                <a class="page-link" href="?page={{ current_page+1 }}&search_term={{ search_term }}" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                            <li class="page-item {% if current_page == total_pages %}disabled{% endif %}">
                                <a class="page-link" href="?page={{ total_pages }}&search_term={{ search_term }}" aria-label="Last">
                                    <span aria-hidden="true">尾页</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
        <div class="card-footer">
            <button id="saveAllBtn" class="btn btn-success">
                <i class="fas fa-save"></i> 保存所有修改
            </button>
        </div>
    </div>
</div>

<!-- 引入必要的JS库 -->
<script src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/toastr.js/latest/toastr.min.js"></script>
<link rel="stylesheet" href="https://cdn.staticfile.org/toastr.js/latest/toastr.min.css">

<script>
$(document).ready(function() {
    // 搜索表单提交
    $('#searchForm').submit(function(e) {
        e.preventDefault();
        var searchTerm = $('#searchInput').val();
        window.location.href = '?page=1&search_term=' + encodeURIComponent(searchTerm);
    });
    
    // 绑定编辑按钮事件
    function bindEditButtons() {
        $('.edit-btn').off('click').on('click', function() {
            var row = $(this).closest('tr');
            enableRowEditing(row);
        });
        
        $('.save-btn').off('click').on('click', function() {
            var row = $(this).closest('tr');
            saveRowChanges(row);
        });
        
        $('.cancel-btn').off('click').on('click', function() {
            var row = $(this).closest('tr');
            cancelRowEditing(row);
        });
    }
    
    // 初始绑定
    bindEditButtons();
    
    // 启用行编辑
    function enableRowEditing(row) {
        row.addClass('editing');
        row.find('.edit-btn').hide();
        row.find('.save-btn').show();
        row.find('.cancel-btn').show();
        
        row.find('td:not(:last-child)').each(function() {
            var cell = $(this);
            var value = cell.text().trim();
            cell.html('<input type="text" class="form-control form-control-sm" value="' + value + '">');
        });
    }
    
    // 保存行修改
    function saveRowChanges(row) {
        var rowData = {};
        var rowId = row.data('id');
        
        row.find('td:not(:last-child)').each(function(index) {
            var columnName = $('#dataTable thead th').eq(index).text();
            var value = $(this).find('input').val();
            rowData[columnName] = value;
            $(this).html(value);
        });
        
        row.removeClass('editing');
        row.find('.save-btn').hide();
        row.find('.cancel-btn').hide();
        row.find('.edit-btn').show();
        
        toastr.success('行数据已更新 (需点击"保存所有修改"按钮永久保存)');
    }
    
    // 取消行编辑
    function cancelRowEditing(row) {
        row.removeClass('editing');
        row.find('td:not(:last-child)').each(function(index) {
            var originalValue = $(this).find('input').val();
            $(this).html(originalValue);
        });
        
        row.find('.save-btn').hide();
        row.find('.cancel-btn').hide();
        row.find('.edit-btn').show();
    }
    
    // 保存所有修改到服务器
    $('#saveAllBtn').click(function() {
        var allData = [];
        $('#dataTable tbody tr').each(function() {
            var rowData = {};
            $(this).find('td:not(:last-child)').each(function(index) {
                var columnName = $('#dataTable thead th').eq(index).text();
                rowData[columnName] = $(this).text().trim();
            });
            allData.push(rowData);
        });
        
        $.ajax({
            url: '/update_lstm_data',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(allData),
            success: function(response) {
                if (response.status === 'success') {
                    toastr.success(response.message);
                    // 刷新页面以获取最新数据
                    setTimeout(function() {
                        window.location.reload();
                    }, 1500);
                } else {
                    toastr.error(response.message);
                }
            },
            error: function(xhr, status, error) {
                toastr.error('保存失败: ' + error);
            }
        });
    });
});
</script>

<style>
.table-responsive {
    overflow-x: auto;
}
tr.editing td {
    background-color: #fffacd;
}
#dataTable th, #dataTable td {
    vertical-align: middle;
    text-align: center;
}
.pagination {
    margin: 0;
}
.dataTables_info {
    padding-top: 0.85em;
}
</style>
{% endblock %}